<template>
    <div class="change-password">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item prop="originPassword">
                <el-input
                    v-model="form.originPassword"
                    type="password"
                    show-password
                    placeholder="请输入原密码"
                    prefix-icon="el-icon-lock"
                    clearable
                />
            </el-form-item>
            <Password ref="passwordRef" v-model="form.password" />
            <el-form-item prop="passwordConfirm">
                <el-input
                    v-model="form.passwordConfirm"
                    type="password"
                    show-password
                    placeholder="请再次输入密码"
                    prefix-icon="el-icon-lock"
                    clearable
                />
            </el-form-item>
        </el-form>
        <el-button class="btn-confirm" type="primary" @click="handleConfirm">确定</el-button>
    </div>
</template>

<script setup>
import { reactive, ref } from "vue";

import Password from "@/components/password/index.vue";

const emits = defineEmits(["reset"]);

const formRef = ref(null);
const passwordRef = ref(null);
const form = reactive({ originPassword: "", password: "", passwordConfirm: "" });

const rules = {
    originPassword: [{ required: true, message: "请输入原密码" }],
    passwordConfirm: [
        { required: true, message: "请再次输入密码" },
        { validator: (_, value) => value === form.password, message: "两次输入密码必须保持一致，请重新输入" },
    ],
};

const handleConfirm = async () => {
    const fns = [passwordRef.value?.validate(), formRef.value.validate()];
    const status = await Promise.all(fns).catch(() => {});
    if (!status) return;

    emits("reset", form);
};
</script>

<style lang="scss" scoped>
.change-password {
    width: 320px;

    .btn-confirm {
        width: 100%;
    }
}
</style>
